package com.feng.cloud.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.feng.cloud.common.annotation.ControllerEndpoint;
import com.feng.cloud.common.request.QueryRequest;
import com.feng.cloud.common.response.RestResponse;
import com.feng.cloud.common.response.TableResultResponse;
import com.feng.cloud.system.entity.LoginLog;
import com.feng.cloud.system.service.LoginLogService;
import com.wuwenze.poi.ExcelKit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @ClassName LoginLogController
 * @Description TODO
 * @Author Better Feng
 * @Date 2019/12/23 10:30
 * @Version 1.0
 **/
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
public class LoginLogController implements ILoginLogController {

    private final LoginLogService loginLogService;

    /**
     * 分页查询日志
     * @param params params
     * @return TableResultResponse<LoginLog>
     */
    @Override
    @GetMapping("page")
    @PreAuthorize("hasAuthority('monitor:loginlog')")
    public TableResultResponse<LoginLog> selectPage(@RequestParam Map<String,Object> params) {
        QueryRequest request = new QueryRequest(params);
        IPage<LoginLog> iPage = loginLogService.selectListByPage(request);
        return new TableResultResponse<>(iPage.getTotal(), iPage.getRecords());
    }

    @DeleteMapping("{logIds}")
    @PreAuthorize("hasAuthority('loginlog:delete')")
    @ControllerEndpoint(operation = "删除操作日志",exceptionMessage = "删除日志失败")
    public RestResponse<Void> deleteLoginLogs(@NotBlank(message = "{required}") @PathVariable String logIds) {
        loginLogService.deleteLogs(Arrays.asList(logIds.split(StringPool.COMMA)));
        return new RestResponse<>();
    }

    @PostMapping("excel")
    @PreAuthorize("hasAuthority('loginlog:export')")
    @ControllerEndpoint(exceptionMessage = "导出Excel失败")
    public void export(@RequestParam Map<String,Object> params, HttpServletResponse response) {
        QueryRequest request = new QueryRequest(params);
        List<LoginLog> logs = loginLogService.selectListByPage(request).getRecords();
        ExcelKit.$Export(LoginLog.class, response).downXlsx(logs, false);
    }
}
